import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { errorResponse, successResponse } from '@/lib/response';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { uploadFile } from '@/lib/storage';
import { randomUUID } from 'crypto';

async function handler(req: NextRequest) {
  const auth = await authenticateRequest(req);
  if (!auth.success || !auth.user) {
    return errorResponse(auth.error || '未认证', 401);
  }

  const formData = await req.formData();
  const file = formData.get('file') as File | null;
  if (!file) return errorResponse('未上传文件', 400);
  if (!file.type.startsWith('image/')) return errorResponse('仅支持图片', 400);

  const bytes = await file.arrayBuffer();
  const buffer = Buffer.from(bytes);
  const safeName = file.name.replace(/\s+/g, '_');
  const objectKey = `${randomUUID()}_${safeName}`;

  const stored = await uploadFile(buffer, objectKey, '');

  const record = await prisma.file.create({
    data: {
      userId: auth.user.id,
      provider: 'minio',
      bucket: process.env.MINIO_BUCKET_NAME || 'tools',
      path: stored.path,
      url: stored.url,
      mimeType: stored.mimeType,
      size: stored.size,
      visibility: 'public',
      category: 'image',
      source: 'admin-upload',
      status: 'active'
    }
  });

  return successResponse({ fileId: record.id, url: record.url, path: record.path });
}

export const POST = withMiddleware(handler);


